package zbase;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRMapArrayDataSource;
import net.sf.jasperreports.view.JasperViewer;

public class StatisticsDialog extends javax.swing.JDialog {

    public StatisticsDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setMinimumSize(this.getSize());
        jFormattedTextField1.setEnabled(false);
        jFormattedTextField2.setEnabled(false);
        jFormattedTextField1.setValue(null);
        jFormattedTextField2.setValue(null);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton3 = new javax.swing.JRadioButton();
        jFormattedTextField1 = new javax.swing.JFormattedTextField();
        jLabel1 = new javax.swing.JLabel();
        jFormattedTextField2 = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Статистика");

        jButton1.setText("Показать статистику");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Отмена");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Выборка по времени"));

        buttonGroup1.add(jRadioButton1);
        jRadioButton1.setSelected(true);
        jRadioButton1.setText("За все время");
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton1ActionPerformed(evt);
            }
        });

        buttonGroup1.add(jRadioButton3);
        jRadioButton3.setText("За период времени:");
        jRadioButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton3ActionPerformed(evt);
            }
        });

        try {
            jFormattedTextField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##.##.####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jFormattedTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jFormattedTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jFormattedTextField1FocusLost(evt);
            }
        });

        jLabel1.setText("по");

        try {
            jFormattedTextField2.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##.##.####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jFormattedTextField2.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jFormattedTextField2.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jFormattedTextField2FocusLost(evt);
            }
        });

        jLabel2.setText("с");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jRadioButton1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jRadioButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jFormattedTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jFormattedTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jRadioButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jRadioButton3)
                    .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jFormattedTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addContainerGap(23, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 19, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
        jLabel1.setEnabled(false);
        jLabel2.setEnabled(false);
        jFormattedTextField1.setEnabled(false);
        jFormattedTextField2.setEnabled(false);
        jFormattedTextField1.setValue(null);
        jFormattedTextField2.setValue(null);
    }//GEN-LAST:event_jRadioButton1ActionPerformed

    private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton3ActionPerformed
        jLabel1.setEnabled(true);
        jLabel2.setEnabled(true);
        jFormattedTextField1.setEnabled(true);
        jFormattedTextField2.setEnabled(true);
    }//GEN-LAST:event_jRadioButton3ActionPerformed

    private void jFormattedTextField1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jFormattedTextField1FocusLost
        if (!ValidateData(jFormattedTextField1.getText(), false)) {
            JOptionPane.showMessageDialog(null, "Ошибка в дате.", "Внимание!", JOptionPane.WARNING_MESSAGE);
            SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
            Calendar ca = Calendar.getInstance();
            ca.add(Calendar.DAY_OF_YEAR, -1);
            jFormattedTextField1.setText(sdf.format(ca.getTime()));
        }
    }//GEN-LAST:event_jFormattedTextField1FocusLost

    private void jFormattedTextField2FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jFormattedTextField2FocusLost
        if (!ValidateData(jFormattedTextField2.getText(), false)) {
            JOptionPane.showMessageDialog(null, "Ошибка в дате.", "Внимание!", JOptionPane.WARNING_MESSAGE);
            SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
            jFormattedTextField2.setText(sdf.format(Calendar.getInstance().getTime()));
        }
    }//GEN-LAST:event_jFormattedTextField2FocusLost

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Calendar dt1 = null;
        Calendar dt2 = null;
        String sdtb = "";
        String sdte = "";
        if (jRadioButton1.isSelected()) {
            sdtb = "'1970-01-01 00:00:00.0'";
            Calendar ca = Calendar.getInstance();
            ca.add(Calendar.YEAR, 1000);
            Integer iyear = ca.get(Calendar.YEAR);
            String year = iyear.toString();
            Integer imonth = ca.get(Calendar.MONTH) + 1;
            String month = imonth.toString();
            if (month.length() < 2) {
                month = "0" + month;
            }
            Integer iday = ca.get(Calendar.DAY_OF_MONTH);
            String day = iday.toString();
            if (day.length() < 2) {
                day = "0" + day;
            }
            sdte = "'" + year + "-" + month + "-" + day + " 00:00:00.0'";
        }
        if (jRadioButton3.isSelected()) {
            if (!ValidateData(jFormattedTextField1.getText(), true)) {
                JOptionPane.showMessageDialog(null, "Ошибка в дате.", "Внимание!", JOptionPane.WARNING_MESSAGE);
                jFormattedTextField1.requestFocus();
                return;
            }
            if (!ValidateData(jFormattedTextField2.getText(), true)) {
                JOptionPane.showMessageDialog(null, "Ошибка в дате.", "Внимание!", JOptionPane.WARNING_MESSAGE);
                jFormattedTextField2.requestFocus();
                return;
            }
            int Year1 = Integer.parseInt(jFormattedTextField1.getText().substring(6, 10));
            int Month1 = Integer.parseInt(jFormattedTextField1.getText().substring(3, 5));
            Month1--;
            int Day1 = Integer.parseInt(jFormattedTextField1.getText().substring(0, 2));
            dt1 = new GregorianCalendar(Year1, Month1, Day1);
            int Year2 = Integer.parseInt(jFormattedTextField2.getText().substring(6, 10));
            int Month2 = Integer.parseInt(jFormattedTextField2.getText().substring(3, 5));
            Month2--;
            int Day2 = Integer.parseInt(jFormattedTextField2.getText().substring(0, 2));
            dt2 = new GregorianCalendar(Year2, Month2, Day2);

            Integer dt1_y = dt1.get(Calendar.YEAR);
            Integer dt1_m = dt1.get(Calendar.MONTH);
            dt1_m++;
            Integer dt1_d = dt1.get(Calendar.DAY_OF_MONTH);
            String dt1s_y = dt1_y.toString();
            String dt1s_m = dt1_m.toString();
            if (dt1s_m.length() < 2) {
                dt1s_m = "0" + dt1s_m;
            }
            String dt1s_d = dt1_d.toString();
            if (dt1s_d.length() < 2) {
                dt1s_d = "0" + dt1s_d;
            }
            Integer dt2_y = dt2.get(Calendar.YEAR);
            Integer dt2_m = dt2.get(Calendar.MONTH);
            dt2_m++;
            Integer dt2_d = dt2.get(Calendar.DAY_OF_MONTH);
            String dt2s_y = dt2_y.toString();
            String dt2s_m = dt2_m.toString();
            if (dt2s_m.length() < 2) {
                dt2s_m = "0" + dt2s_m;
            }
            String dt2s_d = dt2_d.toString();
            if (dt2s_d.length() < 2) {
                dt2s_d = "0" + dt2s_d;
            }
            sdtb = "'" + dt1s_y + "-" + dt1s_m + "-" + dt1s_d + " 00:00:00.000'";
            sdte = "'" + dt2s_y + "-" + dt2s_m + "-" + dt2s_d + " 23:59:59.000'";
        }

        String sql = "SELECT services.servicename, COUNT(*) as kolvo, selectdone.koldone, selectundone.kolundone " +
                "FROM zmain LEFT JOIN services ON zmain.zservice = services.k LEFT JOIN " +
                "(SELECT zmain.zservice, COUNT(*) AS koldone FROM zmain WHERE zmain.zdone = 1 AND zmain.zdatetime BETWEEN " + sdtb + " AND " + sdte + " AND zmain.hide = 0 GROUP BY zmain.zservice) AS selectdone ON zmain.zservice = selectdone.zservice LEFT JOIN " +
                "(SELECT zmain.zservice, COUNT(*) AS kolundone FROM zmain WHERE zmain.zdone = 0 AND zmain.zdatetime BETWEEN " + sdtb + " AND " + sdte + " AND zmain.hide = 0 GROUP BY zmain.zservice) AS selectundone ON zmain.zservice = selectundone.zservice " +
                "WHERE zmain.hide = 0 AND zmain.zdatetime BETWEEN " + sdtb + " AND " + sdte + " GROUP BY zmain.zservice ORDER BY kolvo DESC";

        WaitingWindow ww = new WaitingWindow();

        DB db = new DB();

        ArrayList<Map> lrr = new ArrayList<Map>();
        SimpleDateFormat sdt = new SimpleDateFormat("dd.MM.yyyy HH:mm");

        ResultSet rs = db.getResultSet(sql);
        try {
            Integer rownum = 0;
            while (rs.next()) {
                Map hm = new HashMap();

                rownum++;
                hm.put("rownum", rownum.toString());
                hm.put("service", Vars.getStringFromHex(rs.getString("servicename")));
                Integer zall = rs.getInt("kolvo");
                Integer zdone = rs.getInt("koldone");
                Integer zundone = rs.getInt("kolundone");
                hm.put("zall", zall.toString());
                hm.put("zdone", zdone.toString());
                hm.put("zundone", zundone.toString());

                lrr.add(hm);
            }
        } catch (SQLException ex) {
            System.out.println(ex.toString());
        }
        db.closeResultSet();

        Map[] reportRows = new Map[lrr.size()];
        reportRows = lrr.toArray(reportRows);

        JRMapArrayDataSource dataSource = new JRMapArrayDataSource(reportRows);
        JasperPrint jp = null;
        try {
            Map pm = new HashMap();
            SimpleDateFormat sdtd = new SimpleDateFormat("dd.MM.yyyy");
            if (jRadioButton1.isSelected() || dt1 == null || dt2 == null) {
                pm.put("report_title", "Статистика по заявкам");
            } else {
                pm.put("report_title", "Статистика по заявкам\nс " + sdtd.format(dt1.getTime()) + " по " + sdtd.format(dt2.getTime()));
            }
            jp = JasperFillManager.fillReport("reportstat.jasper", pm, dataSource);
        } catch (JRException ex) {
            System.out.println(ex.toString());
            ww.close();
            return;
        }

        dispose();
        ww.close();

        if (jp.getPages().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Соответствующих запросу заявок не найдено.", "Информация", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        JasperViewer jv = new JasperViewer(jp, false);
        jv.setTitle("Отчет");
        jv.setLocationRelativeTo(null);
        jv.setVisible(true);
        jv.setFitPageZoomRatio();
    }//GEN-LAST:event_jButton1ActionPerformed

    private Boolean ValidateData(String dtstr, Boolean strogo) {
        try {
            int day = Integer.parseInt(dtstr.substring(0, 2));
            if (day > 31 || day == 0) {
                return false;
            }
            int month = Integer.parseInt(dtstr.substring(3, 5));
            month--;
            if (month > 11 || month == -1) {
                return false;
            }
            int year = Integer.parseInt(dtstr.substring(6, 10));
        } catch (NumberFormatException ex) {
            if (strogo) {
                return false;
            }
        }
        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JFormattedTextField jFormattedTextField2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton3;
    // End of variables declaration//GEN-END:variables
}
